# cython: language_level=3
import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import platform
import app.model_phl.util_log as utils
import pandas as pd
import numpy as np
import pickle


def load_data_from_pickle(file_path_name):
    """
    加载pkl格式数据
    :param file_path_name:
    :return:
    """
    current_path = os.path.dirname(__file__)
    file_path_name = file_path_name.replace("./", current_path + "/")
    file_path_name = file_path_name.replace("\\\\", "/")
    with open(file_path_name, "rb") as infile:
        result = pickle.load(infile)
    return result


def p2score(p, pdo=40, base_score=700):
    """
    概率转换为分数的函数
    说明：概率p=坏的概率
    :param p:
    :param pdo:
    :param base_score:
    :return:
    """
    b = pdo / np.log(2)
    a = base_score + b * np.log(1 / 20)
    if p < 0:
        return -99999
    min_p = 1e-9
    max_p = 1 - min_p
    if p >= max_p:
        p = max_p
    elif p <= min_p:
        p = min_p
    score = int(a + b * np.log((1 - p) / (p)))
    if score < 300:
        return 300
    elif score > 900:
        return 900
    else:
        return score


def get_score(data_df, model_path, model_features_path):
    """
    基于模型结果和入模变量结果计算评分
    :param data_df:
    :param model_path:
    :param model_features_path:
    :return:
    """
    # 特征
    online_model = load_data_from_pickle(model_path)
    feature_cols = load_data_from_pickle(model_features_path)
    # 模型输出概率
    prob = pd.Series(
        online_model.predict_proba(data_df[feature_cols])[:, 1], index=data_df.index
    )
    # 转化打分
    model_score = prob.apply(p2score)
    return model_score


def get_user_model_score_main(features):
    """
    计算评分的主函数
    :param features:
    :return:
    """
    try:
        data_df = pd.DataFrame([features])
        data_df.fillna(-999999, inplace=True)

        # 新客V1版本
        creditScoreV1 = -999999

        # 老客V1版本
        old_model_path_v1 = "./model/old_lgbmmodel_v1.pkl"
        old_model_features_path_v1 = "./model/old_lgbmmodel_fea_v1.pkl"
        oldCreditScoreV1 = get_score( data_df, old_model_path_v1, old_model_features_path_v1)[0]

        # 新客V2版本
        # model_path_v1 = "./model/new_lgbmmodel_v2.pkl"
        # model_features_path_v1 = "./model/new_lgbmmodel_fea_v2.pkl"
        # creditScoreV2 = get_score(data_df, model_path_v1, model_features_path_v1)[0]
        creditScoreV2 = -999999

        # 新客V3版本
        # model_path_v3 = './model/new_lgbmmodel_v3.pkl'
        # model_features_path_v3 = './model/new_lgbmmodel_fea_v3.pkl'
        # creditScoreV3 = get_score(data_df, model_path_v3, model_features_path_v3)[0]
        creditScoreV3 = -999999

        return {
            'creditScoreV1': creditScoreV1,
            'oldCreditScoreV1': oldCreditScoreV1,
            'creditScoreV2': creditScoreV2,
            'creditScoreV3': creditScoreV3,
        }
    except Exception as e:
        utils.get_logger().error(e)
        utils.get_logger().error(features)
        return {
            'creditScoreV1': 0,
            'oldCreditScoreV1': 0,
            'creditScoreV2': 0,
            'creditScoreV3': 0,
        }


if __name__ == "__main__":
    新客V2版本测试
    features = {
        "age": 30,
        "smsAllRepayRemindTimeIntervalMedianAllD": -9999,
        "appAllAllInstallIntervalUpdateDaysRepeatCnt14D": -9999,
        "smsAllCashBalanceMax14D": -9999,
        "smsAllCashTimeIntervalMedian60D": -9999,
        "smsAllRelativesTimeIntervalMedianAllD": -9999,
        "smsAllLoanFuzzyAppMsgNunique3D": -9999,
        "smsAllRelativesMsgNunique3D": -9999,
        "smsAllRelativesMessageDaysRepeatCnt1D": -9999,
        "smsAllLoanTimeIntervalAvgAllD": -9999,
        "smsAllCashTimeIntervalMedian3D": -9999,
        "smsAllLoanSuccessTimeIntervalMad3D": -9999,
        "appAllAllInstallIntervalUpdateIntervalMin7D": -9999,
        "appAllbad2InstallIntervalInstallIntervalMax14D": -9999,
        "smsAllCashTimeIntervalMin3D": -9999,
        "smsAllRelativesTimeIntervalMedian1D": -9999,
        "smsAllLoanFuzzyAppTimeIntervalMad14D": -9999,
        "appAllBankInstallIntervalAppNameRepeatCntAllD": -9999,
        "appIsUpdateAllInstallIntervalUpdateIntervalMin60D": -9999,
        "appIsNoUpdateSocialInstallIntervalInstallDaysRepeatCntAllD": -9999,
        "appAllAllInstallIntervalUpdateDaysRepeatCnt60D": -9999,
        "smsAllCashTimeIntervalMax7D": -9999,
        "smsAllCashBalanceStd14D": -9999,
        "smsAllLoanTimeIntervalMax7D": -9999,
        "smsAllLoanSuccessTimeIntervalMax3D": -9999,
        "smsAllCashTimeIntervalMax1D": -9999,
        "appIsNoUpdateAllInstallIntervalInstallDaysNunique60D": -9999,
        "smsAllRelativesMsgNunique1D": -9999,
        "appIsNoUpdatebad2InstallIntervalInstallIntervalMax14D": -9999,
        "smsAllRelativesTimeIntervalMax14D": -9999,
        "smsAllRelativesMsgNunique7D": -9999,
        "smsAllBankTimeIntervalMax60D": -9999,
        "smsAllRelativesMsgNunique30D": -9999,
        "appAllBankInstallIntervalUpdateDaysNuniqueAllD": -9999,
        "smsAllLoanSuccessTimeIntervalAvg7D": -9999,
        "smsAllRelativesMsgRepeatCnt30D": -9999,
        "smsAllLoanFuzzyAppTimeIntervalMedian30D": -9999,
        "appAllAllInstallIntervalInstallIntervalMad7D": -9999,
        "appAllAllInstallIntervalUpdateIntervalMin14D": -9999,
        "smsAllLoanFuzzyAppBalanceSum14D": -9999,
        "appIsUpdateAllInstallIntervalUpdateIntervalMinAllD": -9999,
        "smsAllCashBalanceAvgAllD": -9999,
        "appIsUpdateSocialInstallIntervalUpdateIntervalMedianAllD": -9999,
        "smsAllCashTimeIntervalAvg3D": -9999,
        "appAllAllInstallIntervalInstallIntervalStdAllD": -9999,
        "appIsNoUpdateSocialInstallIntervalAppNameCntAllD": -9999,
    }
    print(get_user_model_score_main(features))
